package com.campus.food.service.impl;

import com.campus.food.mapper.FoodMapper;
import com.campus.food.mapper.MerchantMapper;
import com.campus.food.model.entity.Food;
import com.campus.food.model.entity.Merchant;
import com.campus.food.service.FoodService;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 菜品服务实现类
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@Service
@Transactional
public class FoodServiceImpl implements FoodService {
    
    @Autowired
    private FoodMapper foodMapper;
    
    @Autowired
    private MerchantMapper merchantMapper;
    
    @Override
    public Food addFood(Food food) {
        // 验证必填字段
        validateFood(food);
        
        // 检查商家是否存在且已审核通过
        validateMerchant(food.getMerchantId());
        
        // 设置默认值
        food.setStatus(1); // 默认上架状态
        food.setSales(0); // 默认销量为0
        
        // 保存菜品
        int result = foodMapper.insert(food);
        if (result <= 0) {
            throw new BusinessException("添加菜品失败");
        }
        
        return food;
    }
    
    @Override
    @Transactional(readOnly = true)
    public Food getFoodById(Long id) {
        if (id == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        Food food = foodMapper.selectById(id);
        if (food == null) {
            throw new BusinessException("菜品不存在");
        }
        
        return food;
    }
    
    @Override
    public boolean updateFood(Food food) {
        if (food.getId() == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        // 验证必填字段
        validateFood(food);
        
        // 检查菜品是否存在
        Food existingFood = foodMapper.selectById(food.getId());
        if (existingFood == null) {
            throw new BusinessException("菜品不存在");
        }
        
        // 验证权限（确保只能修改自己商家的菜品）
        if (!existingFood.getMerchantId().equals(food.getMerchantId())) {
            throw new BusinessException("无权限修改此菜品");
        }
        
        return foodMapper.updateById(food) > 0;
    }
    
    @Override
    public boolean updateFoodStatus(Long id, Integer status, Long merchantId) {
        if (id == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        if (status == null || (status != 0 && status != 1)) {
            throw new BusinessException("菜品状态无效");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查菜品是否存在
        Food food = foodMapper.selectById(id);
        if (food == null) {
            throw new BusinessException("菜品不存在");
        }
        
        // 验证权限（确保只能修改自己商家的菜品）
        if (!food.getMerchantId().equals(merchantId)) {
            throw new BusinessException("无权限修改此菜品状态");
        }
        
        return foodMapper.updateStatus(id, status) > 0;
    }
    
    @Override
    public boolean deleteFood(Long id, Long merchantId) {
        if (id == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 检查菜品是否存在
        Food food = foodMapper.selectById(id);
        if (food == null) {
            throw new BusinessException("菜品不存在");
        }
        
        // 验证权限（确保只能删除自己商家的菜品）
        if (!food.getMerchantId().equals(merchantId)) {
            throw new BusinessException("无权限删除此菜品");
        }
        
        return foodMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getFoodsByMerchantId(Long merchantId, Integer status) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        return foodMapper.selectByMerchantId(merchantId, status);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getFoodListByMerchant(Long merchantId, int page, int size, String name, String category, Integer status) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        int offset = (page - 1) * size;
        return foodMapper.selectPageByMerchant(merchantId, offset, size, name, category, status);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getFoodCountByMerchant(Long merchantId, String name, String category, Integer status) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        return foodMapper.selectCountByMerchant(merchantId, name, category, status);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getFoodListForUser(Long merchantId, int page, int size, String name, String category) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        int offset = (page - 1) * size;
        return foodMapper.selectPageForUser(merchantId, offset, size, name, category);
    }
    
    @Override
    @Transactional(readOnly = true)
    public long getFoodCountForUser(Long merchantId, String name, String category) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        return foodMapper.selectCountForUser(merchantId, name, category);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getFoodsByCategory(Long merchantId, String category) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (!StringUtils.hasText(category)) {
            throw new BusinessException("分类不能为空");
        }
        
        return foodMapper.selectByCategory(merchantId, category);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<String> getFoodCategories(Long merchantId) {
        if (merchantId == null) {
            return foodMapper.selectCategories(null);
        }
        
        return foodMapper.selectCategoriesByMerchant(merchantId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getHotFoods(Long merchantId, Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 10; // 默认返回10个
        }
        
        return foodMapper.selectHotFoods(merchantId, limit);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getFoodsByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("菜品ID列表不能为空");
        }
        
        return foodMapper.selectByIds(ids);
    }
    
    @Override
    public boolean increaseSales(Long id, Integer quantity) {
        if (id == null) {
            throw new BusinessException("菜品ID不能为空");
        }
        
        if (quantity == null || quantity <= 0) {
            throw new BusinessException("销量增加数量必须大于0");
        }
        
        // 检查菜品是否存在
        Food food = foodMapper.selectById(id);
        if (food == null) {
            throw new BusinessException("菜品不存在");
        }
        
        return foodMapper.increaseSales(id, quantity) > 0;
    }
    
    @Override
    public boolean deleteFoodBatch(List<Long> ids, Long merchantId) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("菜品ID列表不能为空");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 验证所有菜品都属于当前商家
        for (Long id : ids) {
            Food food = foodMapper.selectById(id);
            if (food == null) {
                throw new BusinessException("菜品不存在：" + id);
            }
            if (!food.getMerchantId().equals(merchantId)) {
                throw new BusinessException("无权限删除菜品：" + id);
            }
        }
        
        return foodMapper.deleteBatch(ids) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> searchFoods(String keyword, int page, int size, Long merchantId, String category, Double minPrice, Double maxPrice) {
        int offset = (page - 1) * size;
        return foodMapper.searchFoods(keyword, offset, size, merchantId, category, minPrice, maxPrice);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getRecommendedFoods(Long merchantId, int limit) {
        if (limit <= 0) {
            limit = 10; // 默认返回10个
        }
        
        return foodMapper.selectRecommendedFoods(merchantId, limit);
    }
    
    @Override
    public boolean updateFoodStatusBatch(List<Long> ids, Integer status, Long merchantId) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("菜品ID列表不能为空");
        }
        
        if (status == null || (status != 0 && status != 1)) {
            throw new BusinessException("菜品状态无效");
        }
        
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        // 验证所有菜品都属于当前商家
        for (Long id : ids) {
            Food food = foodMapper.selectById(id);
            if (food == null) {
                throw new BusinessException("菜品不存在：" + id);
            }
            if (!food.getMerchantId().equals(merchantId)) {
                throw new BusinessException("无权限修改菜品：" + id);
            }
        }
        
        return foodMapper.updateStatusBatch(ids, status) > 0;
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getFoodSalesStats(Long merchantId, String startDate, String endDate) {
        if (merchantId == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        return foodMapper.selectSalesStats(merchantId, startDate, endDate);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Food> getAllFoods(int page, int size, Long merchantId, String category, Integer status) {
        int offset = (page - 1) * size;
        return foodMapper.selectAllForAdmin(offset, size, merchantId, category, status);
    }
    
    /**
     * 验证菜品信息
     */
    private void validateFood(Food food) {
        if (food == null) {
            throw new BusinessException("菜品信息不能为空");
        }
        
        if (food.getMerchantId() == null) {
            throw new BusinessException("商家ID不能为空");
        }
        
        if (!StringUtils.hasText(food.getName())) {
            throw new BusinessException("菜品名称不能为空");
        }
        
        if (food.getPrice() == null || food.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("菜品价格必须大于0");
        }
        
        if (!StringUtils.hasText(food.getCategory())) {
            throw new BusinessException("菜品分类不能为空");
        }
        
        // 验证菜品名称长度
        if (food.getName().length() > 50) {
            throw new BusinessException("菜品名称不能超过50个字符");
        }
        
        // 验证价格范围
        if (food.getPrice().compareTo(new BigDecimal("9999.99")) > 0) {
            throw new BusinessException("菜品价格不能超过9999.99元");
        }
        
        // 验证分类长度
        if (food.getCategory().length() > 20) {
            throw new BusinessException("菜品分类不能超过20个字符");
        }
        
        // 验证描述长度
        if (StringUtils.hasText(food.getDescription()) && food.getDescription().length() > 500) {
            throw new BusinessException("菜品描述不能超过500个字符");
        }
    }
    
    /**
     * 验证商家信息
     */
    private void validateMerchant(Long merchantId) {
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant == null) {
            throw new BusinessException("商家不存在");
        }
        
        if (merchant.getStatus() != 1) {
            throw new BusinessException("商家未通过审核，无法添加菜品");
        }
    }
} 